package cn.zhc.com.http.interceptors;

import android.text.TextUtils;

import cn.zhc.com.utils.UtilsLog;

import java.io.IOException;

import okhttp3.Headers;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okio.Buffer;

/**
 * Created by zhy on 16/3/1.
 */
public class LoggerInterceptor implements Interceptor {
    public static final String TAG_DEFAULT = "OkHttpUtils";
    private String tag;
    /**
     * 是否打印服务器响应日志
     */
    private boolean showResponseLog;
    private boolean showRequestLog;

    public LoggerInterceptor(String tag, boolean showResponseLog, boolean showRequestLog) {
        if (TextUtils.isEmpty(tag)) {
            tag = TAG_DEFAULT;
        }
        this.showResponseLog = showResponseLog;
        this.showRequestLog = showRequestLog;
        this.tag = tag;
    }

    @Override
    public Response intercept(Chain chain) {
        Request request = null;
        Response response = null;
        try {
            request = chain.request();
            //添加通用的header，此外注意还有参数部分也要添加到header，在其他地方
            request = request.newBuilder()
                    .header("X-VERSION", "0")//1表示需要AES加密，解密请在回调中自行处理
                    .header("X-CLIENT-TYPE", "Android")
                    .build();
            request.cacheControl();
            logForRequest(request);
            response = chain.proceed(request);
            return logForResponse(response);
        } catch (Exception e) {
            e.printStackTrace();
            return response;
        }

    }

    private Response logForResponse(Response response) {
        if (!showResponseLog) {
            return response;
        }
        try {
            //===>response log

            UtilsLog.d(tag, "********************* HTTP Response log start *********************");
            Response.Builder builder = response.newBuilder();
            Response clone = builder.build();
            UtilsLog.d(tag, "url : " + clone.request().url());
            UtilsLog.d(tag, "code : " + clone.code());
            UtilsLog.d(tag, "protocol : " + clone.protocol());
            if (!TextUtils.isEmpty(clone.message()))
                UtilsLog.d(tag, "message : " + clone.message());
            ResponseBody body = clone.body();
            if (body != null) {
                MediaType mediaType = body.contentType();
                if (mediaType != null) {
                    UtilsLog.d(tag, "responseBody's contentType : " + mediaType.toString());
                    if (isText(mediaType)) {
                        String resp = body.string();
                        UtilsLog.d(tag, "responseBody's content : " + resp);

                        body = ResponseBody.create(mediaType, resp);
                        return response.newBuilder().body(body).build();
                    } else {
                        UtilsLog.d(tag, "responseBody's content : " + " maybe [file part] , too large too print , ignored!");
                    }
                }
            }
            UtilsLog.d(tag, "********************* HTTP Response log end *********************");

        } catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }

    private void logForRequest(Request request) {
        if (!this.showRequestLog) {
            return;
        }
        try {
            //===>request log

            String url = request.url().toString();
            Headers headers = request.headers();

            UtilsLog.d(tag, "********************* HTTP Request log start *********************");
            UtilsLog.d(tag, "method : " + request.method());
            UtilsLog.d(tag, "url : " + url);
            if (headers != null && headers.size() > 0) {
                UtilsLog.d(tag, "headers : " + headers.toString());
            }
            RequestBody requestBody = request.body();
            if (requestBody != null) {
                MediaType mediaType = requestBody.contentType();
                if (mediaType != null) {
                    UtilsLog.d(tag, "requestBody's contentType : " + mediaType.toString());
                    if (isText(mediaType)) {
                        UtilsLog.d(tag, "requestBody's content : " + bodyToString(request));
                    } else {
                        UtilsLog.d(tag, "requestBody's content : " + " maybe [file part] , too large too print , ignored!");
                    }
                }
            }
            UtilsLog.d(tag, "********************* HTTP Request log end *********************");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private boolean isText(MediaType mediaType) {
        if (mediaType.type() != null && mediaType.type().equals("text")) {
            return true;
        }
        if (mediaType.subtype() != null) {
            if (mediaType.subtype().equals("json") ||
                    mediaType.subtype().equals("xml") ||
                    mediaType.subtype().equals("html") ||
                    mediaType.subtype().equals("webviewhtml")
                    )
                return true;
        }
        return false;
    }

    private String bodyToString(final Request request) {
        try {
            final Request copy = request.newBuilder().build();
            final Buffer buffer = new Buffer();
            copy.body().writeTo(buffer);
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "something error when show requestBody.";
        }
    }
}
